import { Location } from '@angular/common';
import { Component, inject, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { PageHeaderModule } from '@delon/abc/page-header';
import { STColumn, STModule } from '@delon/abc/st';
import { SVModule } from '@delon/abc/sv';
import { _HttpClient } from '@delon/theme';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzCardModule } from 'ng-zorro-antd/card';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzGridModule } from 'ng-zorro-antd/grid';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzRadioModule } from 'ng-zorro-antd/radio';
import { NzSwitchModule } from 'ng-zorro-antd/switch';
import { NzTagModule } from 'ng-zorro-antd/tag';
import { NzFormatEmitEvent, NzTreeModule } from 'ng-zorro-antd/tree';
import { Api } from 'src/app/shared/api/api';
import { DELETED_STATUS_BADGE, MENU_TYPE_ENUM } from 'src/app/shared/constant/common-constant';
import { ResponseCode } from 'src/app/shared/response.code';

@Component({
  selector: 'app-system-role-menu',
  templateUrl: './role-menu.component.html',
  imports: [
    PageHeaderModule,
    NzButtonModule,
    NzTagModule,
    NzGridModule,
    NzCardModule,
    NzTreeModule,
    STModule,
    NzSwitchModule,
    FormsModule,
    SVModule,
    NzIconModule,
    NzRadioModule
  ]
})
export class RoleMenuComponent implements OnInit {
  role: NzSafeAny = {};
  currentMenuPermissions: NzSafeAny[] = [];
  currentMenuType: NzSafeAny = undefined;
  menuTree: NzSafeAny[] = [];
  allMenuTree: NzSafeAny[] = [];

  permissionColmuns: STColumn[] = [
    { title: '序号', type: 'no', width: 60 },
    { title: '权限', index: 'permission' },
    { title: '备注', index: 'remark' },
    { title: '状态', index: 'deleted', type: 'badge', badge: DELETED_STATUS_BADGE, width: 100 },
    { title: '开启', render: 'operation', width: 100 }
  ];
  protected readonly http = inject(_HttpClient);
  private readonly msg = inject(NzMessageService);
  protected readonly location = inject(Location);
  private readonly router = inject(ActivatedRoute);
  constructor() {
    this.router.queryParams.subscribe((res: NzSafeAny) => {
      if (!res) {
        this.msg.error('参数有误');
        return;
      }
      this.role = res;
    });
  }

  ngOnInit(): void {
    this.queryMenuConfig();
  }

  backList() {
    this.location.back();
  }
  getTypleList(): Array<{ label: string; value: number }> {
    return [{ label: '全部', value: undefined } as NzSafeAny].concat(MENU_TYPE_ENUM);
  }
  queryMenuConfig() {
    this.http
      .get(`${Api.BaseAntMenuApi}/role/config/vo`, { roleId: this.role.id, super: this.role.code == 'SUPER' })
      .subscribe((res: NzSafeAny) => {
        if (res && res.code === ResponseCode.SUCCESS) {
          this.setMenuConfig(res.data);
        } else {
          this.setMenuConfig(null);
        }
      });
  }

  setMenuConfig(data: NzSafeAny): void {
    if (!data) {
      this.menuTree = [];
      this.allMenuTree = [];
    } else {
      this.menuTree = data;
      this.allMenuTree = data;
    }
  }

  menuClick(event: NzFormatEmitEvent): void {
    console.log(event);
    this.currentMenuPermissions = [];

    setTimeout(() => {
      let permissions = event.node?.origin['permissionList'] || [];
      this.currentMenuPermissions = permissions;
    }, 500);
  }

  filterMenuTree(e: NzSafeAny) {
    if (e) {
      this.menuTree = this.allMenuTree.filter((item: NzSafeAny) => item.type === e);
    } else {
      this.menuTree = this.allMenuTree;
    }
    this.currentMenuPermissions = [];
  }

  refreshPermission(index: number, event: NzSafeAny) {
    this.currentMenuPermissions[index].checked = event;
    this.currentMenuPermissions[index].selected = event;
  }

  save() {
    this.http.post(`${Api.BaseAntMenuApi}/role/config/vo/${this.role.id}`, this.allMenuTree).subscribe((res: NzSafeAny) => {
      if (res && res.code === ResponseCode.SUCCESS) {
        this.queryMenuConfig();
        this.msg.success('保存成功!');
      } else {
        this.msg.error(res ? (res.message ? res.message : '保存失败，未知原因') : '保存失败，未知原因');
      }
    });
  }
}
